/* ***** BEGIN LICENSE BLOCK *****
 *   Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 * 
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is Save File to.
 *
 * The Initial Developer of the Original Code is
 * Atte Kemppilä.
 * Portions created by the Initial Developer are Copyright (C) 2009
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 * 
 * ***** END LICENSE BLOCK ***** */


var EXPORTED_SYMBOLS =
[
    "upgrade"
];

const Cc = Components.classes;
const Ci = Components.interfaces;
const Cr = Components.results;
const Cu = Components.utils;

Cu.import("resource://savefileto/common.jsm");
Cu.import("resource://savefileto/constants.jsm");
Cu.import("resource://savefileto/Entry.jsm");
Cu.import("resource://savefileto/savefileto.jsm");

const compareVersions = Cc["@mozilla.org/xpcom/version-comparator;1"].getService(Ci.nsIVersionComparator).compare;
const prefSvc = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefService);


function upgrade(version)
{
    var lastVersion = getLastVersion();
    
    // not up-to-date?
    if (compareVersions(version, lastVersion) != 0)
    {
        // downgraded?
        if (compareVersions(version, lastVersion) < 0)
            throw new Error("last version (" + lastVersion + ") is higher than current version (" + version + "). extension may not work correctly.");
        
        // upgrade if not first run
        if (compareVersions(lastVersion, "0") != 0)
            vLatest.upgrade(lastVersion);
        
        setLastVersion(version);
    }
    
    return lastVersion
}


var v1 =
{
    prefs: prefSvc.getBranch("extensions.savefileto."),
    
    types: ["page", "link", "image"],
    
    get recentFoldersOnTop() { return getPref(this.prefs, "recentFoldersOnTop", false); },
    
    get recentFoldersEnabled() { return (getPref(this.prefs, "recentFoldersN", 5) > 0); },
    
    getFolders: function(type)
    {
        return this.parseFoldersPref(type + ".rootFolders");
    },
    
    getRecent: function(type)
    {
        return this.parseFoldersPref(type + ".recentFolders");
    },
    
    parseFoldersPref: function(name)
    {
        var value = getPref(this.prefs, name, "");
        var folders = this.parseFolders(value);
        return folders;
    },
    
    // http://hg.mozdev.org/savefileto/file/1.3.2/content/util.js#l78
    parseFolders: function(str)
    {
        var folders = [];
        if (str)
        {
            // <name1>*<path1>|<name2>*<path2>|...
            var entries = str.split("|");
            for (var i = 0; i < entries.length; i++)
            {
                var values = entries[i].split("*");
                var folder = {name: values[0], path: values[1]};
                folders.push(folder);
            }
        }
        return folders;
    }
}


var v2 =
{
    version: "2.0b1",
    
    prefs: prefSvc.getBranch(EXT_PREF_BRANCH),
    
    // preference mappings: 1.x -> 2.x {v1: v2}
    prefMappings:
    {
        "clearRecentFolders": {name: "clearRecent"},
        "lookahead": {name: "trimEmptyMenu"},
        "maxMenuLength": {},
        "prompt": {},
        "recentFoldersN": {name: "recentSize", value: function(value) { return ((value < 1) ? 5 : Math.min(10, value)); }},
        "responseHeaderTimeout": {name: "responseTimeout"},
        "page.enabled": {},
        "link.enabled": {},
        "image.enabled": {}
    },
    
    upgrade: function(version)
    {
        if (compareVersions(version, this.version) >= 0)
            return;
        
        try
        {
            upgradePrefs(v1.prefs, this.prefs, this.prefMappings);
            this.upgradeEntriesPrefs();
            this.upgradeRecentPrefs();
            setLastVersion(this.version);
            v1.prefs.deleteBranch("");
        }
        catch (e)
        {
            clearPrefs(this.prefs);
            throw e;
        }
    },
    
    upgradeEntriesPrefs: function()
    {
        var recentFoldersEnabled = v1.recentFoldersEnabled;
        var recentFoldersOnTop = v1.recentFoldersOnTop;
        
        // page, link, image
        for each (var type in v1.types)
        {
            var entries = [];
            
            if (recentFoldersEnabled && recentFoldersOnTop)
                entries.push(recentEntry, separatorEntry);
            
            var folders = v1.getFolders(type);
            var folderEntries = [{type: "folder", label: folder.name, path: folder.path, menu: true} for each (folder in folders)];
            entries = entries.concat(folderEntries);
            entries.push(separatorEntry);
            
            if (recentFoldersEnabled && (! recentFoldersOnTop))
                entries.push(recentEntry, separatorEntry);
            
            entries.push(savefileto.getOpenPrefsEntry(type));
            
            this.setEntriesPref(type + ".entries", entries);
        }
        
        // file
        var entries = this.getEntriesPref("file.entries");
        
        if (! recentFoldersEnabled)
            entries.splice(0, 2);
        else if (! recentFoldersOnTop)
            Array.prototype.splice.apply(entries, [-1, 0].concat(entries.splice(0, 2)));
        
        this.setEntriesPref("file.entries", entries);
    },
    
    upgradeRecentPrefs: function()
    {
        for each (var type in v1.types)
        {
            var recent = v1.getRecent(type);
            var recentEntries = [{type: "folder", label: folder.name, path: folder.path, menu: false} for each (folder in recent)];
            
            this.setEntriesPref(type + ".recent", recentEntries);
        }
    },
    
    getEntriesPref: function(name)
    {
        var value = getPref(this.prefs, name, "[]");
        var json = JSON.parse(value);
        return json;
    },
    
    setEntriesPref: function(name, value)
    {
        var json = JSON.stringify(value);
        setPref(this.prefs, name, json);
    }
}


var vLatest = v2;


function getLastVersion()
{
    var version = getPref(vLatest.prefs, "lastVersion", "0");
    
    if (version == "0")
        version = getPref(v1.prefs, "lastVersion", "0");
    
    return version;
}


function setLastVersion(version)
{
    setPref(vLatest.prefs, "lastVersion", version);
}


function upgradePrefs(oldPrefs, newPrefs, mappings)
{
    var children = oldPrefs.getChildList("", {});
    for each (var oldName in children)
    {
        if (oldName in mappings)
        {
            try
            {
                var oldValue = getPref(oldPrefs, oldName);
                var mapping = mappings[oldName];
                var newName = (("name" in mapping) ? mapping.name : oldName);
                var newValue = (("value" in mapping) ? mapping.value(oldValue) : oldValue);
                setPref(newPrefs, newName, newValue);
            }
            catch (e) { Cu.reportError(e); }
        }
    }
}


function clearPrefs(prefs)
{
    var children = prefs.getChildList("", {});
    for each (var child in children)
        if (prefs.prefHasUserValue(child))
            prefs.clearUserPref(child);
}
